Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

363
Views
CastError: Cast to ObjectId failed for value "XXXXXXXXXX" (type string) at path "_id" for model "XXXX"

I'm a beginner.

when i'm testing route with wrong (short) ID, for example instead of "6261220286e8d5e7ee6f221e" i'm putting "6261220286e8d5e7ee6f221" node app crashes with this error:

Screenshot of Node ERROR

here is the route code:

router.put('/:id', async (req, res) => {
    //Validate with Joi
    const { error } = validateGenre(req.body);
    //If invalid, return 400 - Bad Request.
    if (error) return res.status(400).send(error.details[0].message);
    //Look up the genre and Update.
    const genre = await Genre.findByIdAndUpdate(req.params.id, { name: req.body.name }, { new: true })
    //If not exists, return 404.
    if (!genre) return res.status(404).send('The genre with the given ID was not found');
    //Return ubdated genre.
    res.send(genre);
});

function validateGenre(genre) {
    const schema = Joi.object({ name: Joi.string().min(3).max(50).required() });
    return schema.validate(genre);
}

here also Genre schema:

const genreSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50,
    }
});

const Genre = new mongoose.model('Genre', genreSchema);

My question is: How to handle this type of error, or how to validate requested ID length to return proper message to the client.

Sorry again, I'm really a beginner and thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Have you tried using try catch ??, in catch section you can do response with status 500 and an error message thrown by Genre

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!